package com.hh.TreeQuestions;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hanghao
 * @Date 2023/7/4 11:14
 * @Version 1.0
 * 二叉树的所有路径
 * easy
 */

public class No257 {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null) return res;
        List<Integer> paths = new ArrayList<>();
        traversal(root, paths, res);
        return res;
    }

    private void traversal(TreeNode root, List<Integer> paths, List<String> res) {
        paths.add(root.val);
        //如果遇到了叶子结点
        if(root.left == null && root.right == null) {
            //将这条路径上的结果记录下来
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < paths.size() - 1; i++) {
                sb.append(paths.get(i)).append("->");
            }
            sb.append(paths.get(paths.size() - 1));
            res.add(sb.toString());
            return;
        }
        //如果没遇到叶子结点
        if(root.left != null) {
            traversal(root.left, paths, res);
            paths.remove(paths.size() - 1); //回溯
        }
        if(root.right != null) {
            traversal(root.right, paths, res);
            paths.remove(paths.size() - 1); //回溯
        }
    }
}
